package talayaco.gui;

import java.util.Calendar;

import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;

import talayaco.interfaz.GestionCorralesINT;
import talayaco.utils.DateUtils;
import talayaco.utils.ErrorUtils;
import talayaco.utils.StringUtils;

public class PesajeCorralesV2 extends javax.swing.JInternalFrame {

	static final long serialVersionUID = 7602781807685511417L;

	public PesajeCorralesV2() {
		initComponents();
	}

	private void initComponents() {

		// TODO jLabel2 = new javax.swing.JLabel();
		jPanel1 = new javax.swing.JPanel();
		jLabel1 = new javax.swing.JLabel();
		jLabel3 = new javax.swing.JLabel();
		jLabel4 = new javax.swing.JLabel();
		jLabel5 = new javax.swing.JLabel();
		jComboBox1 = new javax.swing.JComboBox();
		jTextField1 = new javax.swing.JTextField();
		jButton4 = new javax.swing.JButton();
		jButton5 = new javax.swing.JButton();
		jScrollPane1 = new javax.swing.JScrollPane();
		jTable1 = new javax.swing.JTable();
		jButton1 = new javax.swing.JButton();
		jButton2 = new javax.swing.JButton();
		pieDePagina = new javax.swing.JTextField();
		jTextField2 = new javax.swing.JTextField();

		this.setTitle("Pesaje de Corrales");
		this.setResizable(false);

		nombreCorral = "";
		cantidad = "";
		i = 0;

		setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

		try {
			nombreCorrales = GestionCorralesINT.getNombreCorrales();
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(this, ErrorUtils.ERROR_INESPERADO,
					"ERROR INESPERADO", JOptionPane.ERROR_MESSAGE);
		}

		jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null,
				"Pesaje de los Corrales",
				javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
				javax.swing.border.TitledBorder.DEFAULT_POSITION,
				new java.awt.Font("Tahoma", 0, 11))); // NOI18N

		jLabel1.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		jLabel1.setText("Fecha");

		jLabel3.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		Calendar fecha = Calendar.getInstance();
		jLabel3.setText(DateUtils.getFechaEnLetras(fecha));

		jTextField2.setFont(new java.awt.Font("Tahoma", 0, 11));

		jLabel3.setEnabled(false);

		jLabel4.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		jLabel4.setText("Corral");

		jLabel5.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		jLabel5.setText("Cantidad");

		jComboBox1.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		jComboBox1
				.setModel(new javax.swing.DefaultComboBoxModel(nombreCorrales));
		jComboBox1.addItemListener(new java.awt.event.ItemListener() {
			public void itemStateChanged(java.awt.event.ItemEvent evt) {
				jComboBox1ItemStateChanged(evt);
			}
		});

		jButton4.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		jButton4.setText("Agregar");
		jButton4.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton4ActionPerformed(evt);
			}
		});

		jButton5.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		jButton5.setText("Eliminar");
		jButton5.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton5ActionPerformed(evt);
			}
		});

		tabla = new String[][] { { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" },
				{ "", "" }, { "", "" }, { "", "" }, { "", "" }, { "", "" }, };

		jTable1.setModel(new javax.swing.table.DefaultTableModel(tabla,
				new String[] { "Corral", "Pesaje" }) {
			private static final long serialVersionUID = 1L;

			@Override
			public boolean isCellEditable(int fila, int columna) {
				return false;
			}
		});
		jScrollPane1.setViewportView(jTable1);

		javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(
				jPanel1);
		jPanel1.setLayout(jPanel1Layout);
		jPanel1Layout
				.setHorizontalGroup(jPanel1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING,
																false)
														.addComponent(
																jLabel1,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																Short.MAX_VALUE)
														.addComponent(
																jLabel5,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																Short.MAX_VALUE)
														.addComponent(
																jLabel4,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																Short.MAX_VALUE))
										.addPreferredGap(
												javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																jTextField2,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																99,
																Short.MAX_VALUE)
														.addComponent(
																jComboBox1, 0,
																99,
																Short.MAX_VALUE)
														.addComponent(
																jTextField1,
																javax.swing.GroupLayout.Alignment.TRAILING,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																99,
																Short.MAX_VALUE))
										.addGap(18, 18, 18)
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.LEADING)
														.addComponent(
																jButton4,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																Short.MAX_VALUE)
														.addComponent(
																jButton5,
																javax.swing.GroupLayout.DEFAULT_SIZE,
																69,
																Short.MAX_VALUE))
										.addGap(18, 18, 18)
										.addComponent(
												jScrollPane1,
												javax.swing.GroupLayout.PREFERRED_SIZE,
												207,
												javax.swing.GroupLayout.PREFERRED_SIZE)
										.addContainerGap()));
		jPanel1Layout
				.setVerticalGroup(jPanel1Layout
						.createParallelGroup(
								javax.swing.GroupLayout.Alignment.LEADING)
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addContainerGap()
										.addGroup(
												jPanel1Layout
														.createParallelGroup(
																javax.swing.GroupLayout.Alignment.CENTER)
														.addGroup(
																jPanel1Layout
																		.createSequentialGroup()
																		.addComponent(
																				jTextField2,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGap(7,
																				7,
																				7)
																		.addComponent(
																				jComboBox1,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				javax.swing.GroupLayout.DEFAULT_SIZE,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGap(7,
																				7,
																				7)
																		.addComponent(
																				jTextField1,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				21,
																				javax.swing.GroupLayout.PREFERRED_SIZE))
														.addGroup(
																jPanel1Layout
																		.createSequentialGroup()
																		.addComponent(
																				jButton4,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				21,
																				javax.swing.GroupLayout.PREFERRED_SIZE)
																		.addGap(6,
																				6,
																				6)
																		.addComponent(
																				jButton5,
																				javax.swing.GroupLayout.PREFERRED_SIZE,
																				21,
																				javax.swing.GroupLayout.PREFERRED_SIZE))
														.addGroup(
																jPanel1Layout
																		.createSequentialGroup()
																		.addComponent(
																				jLabel1)
																		.addGap(13,
																				13,
																				13)
																		.addComponent(
																				jLabel4)
																		.addGap(14,
																				14,
																				14)
																		.addComponent(
																				jLabel5)))
										.addContainerGap())
						.addGroup(
								jPanel1Layout
										.createSequentialGroup()
										.addGap(11, 11, 11)
										.addComponent(
												jScrollPane1,
												javax.swing.GroupLayout.DEFAULT_SIZE,
												74, Short.MAX_VALUE)
										.addContainerGap(11, Short.MAX_VALUE)));

		jButton1.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		jButton1.setText("Aceptar");
		jButton1.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton1ActionPerformed(evt);
			}
		});

		jButton2.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		jButton2.setText("Cancelar");
		jButton2.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jButton2ActionPerformed(evt);
			}
		});

		pieDePagina.setBackground(new java.awt.Color(204, 204, 205));
		pieDePagina.setEditable(false);
		pieDePagina.setFont(new java.awt.Font("Tahoma", 0, 11)); // NOI18N
		pieDePagina.setHorizontalAlignment(javax.swing.JTextField.CENTER);
		pieDePagina
				.setText("Ingrese los pesajes en kilogramos de todos los corrales de hoy.");

		javax.swing.GroupLayout layout = new javax.swing.GroupLayout(
				getContentPane());
		getContentPane().setLayout(layout);
		layout.setHorizontalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.LEADING,
												false)
												.addComponent(
														jPanel1,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addGroup(
														javax.swing.GroupLayout.Alignment.TRAILING,
														layout.createSequentialGroup()
																.addComponent(
																		pieDePagina)
																.addGap(18, 18,
																		18)
																.addComponent(
																		jButton2)
																.addGap(18, 18,
																		18)
																.addComponent(
																		jButton1)))
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));
		layout.setVerticalGroup(layout
				.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
				.addGroup(
						layout.createSequentialGroup()
								.addContainerGap()
								.addComponent(jPanel1,
										javax.swing.GroupLayout.PREFERRED_SIZE,
										javax.swing.GroupLayout.DEFAULT_SIZE,
										javax.swing.GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(
										javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
								.addGroup(
										layout.createParallelGroup(
												javax.swing.GroupLayout.Alignment.BASELINE)
												.addComponent(
														pieDePagina,
														javax.swing.GroupLayout.PREFERRED_SIZE,
														javax.swing.GroupLayout.DEFAULT_SIZE,
														javax.swing.GroupLayout.PREFERRED_SIZE)
												.addComponent(jButton1)
												.addComponent(jButton2))
								.addContainerGap(
										javax.swing.GroupLayout.DEFAULT_SIZE,
										Short.MAX_VALUE)));

		pack();
	}// </editor-fold>

	private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

		try {
			String fechaAux = jTextField2.getText();
			String valida = DateUtils.esValida(fechaAux);

			/*
			 * String fechaAux = fecha.get(Calendar.DATE) + "/" +
			 * (fecha.get(Calendar.MONTH) + 1) + "/" + fecha.get(Calendar.YEAR);
			 */

			if (!valida.equals("")) {
				JOptionPane.showMessageDialog(this, valida, "ERROR",
						JOptionPane.ERROR_MESSAGE);
			} else {

				String day;
				String month;
				String year;

				String[] datosAux = fechaAux.split("/");
				day = datosAux[0];
				month = datosAux[1];
				year = datosAux[2];

				String fechaConsulta = year + "-" + month + "-" + day;

				/*
				 * String fechaConsulta = fecha.get(Calendar.YEAR) + "-" +
				 * (fecha.get(Calendar.MONTH) + 1) + "-" +
				 * fecha.get(Calendar.DATE);
				 */

				if (GestionCorralesINT.existePesajeFecha(fechaConsulta)) {
					JOptionPane.showMessageDialog(this,
							ErrorUtils.PESAJE_EXISTENTE + fechaAux, "ERROR",
							JOptionPane.ERROR_MESSAGE);
				} else if (this.todosCargados()) {
					GestionCorralesINT.setPesajes(fechaAux, tabla,
							nombreCorrales.length - 1, this);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(this, ErrorUtils.ERROR_INESPERADO,
					"ERROR INESPERADO", JOptionPane.ERROR_MESSAGE);
		}
	}

	private Boolean todosCargados() {

		String corrales[] = new String[nombreCorrales.length - 1];
		for (int j = 0; j < corrales.length; j++) {
			corrales[j] = nombreCorrales[j + 1];
		}

		int encontrado = 0;
		for (int i = 0; i < corrales.length; i++) {
			for (int j = 0; j < tabla.length; j++)
				if (tabla[j][0].equals(corrales[i]))
					encontrado++;
			if (encontrado == 0) {
				JOptionPane.showMessageDialog(this, ErrorUtils.FALTAN_PESAJES
						+ corrales[i], "ERROR", JOptionPane.ERROR_MESSAGE);
				return false;
			} else if (encontrado > 1) {
				JOptionPane.showMessageDialog(this, ErrorUtils.SOBRAN_PESAJES
						+ corrales[i], "ERROR", JOptionPane.ERROR_MESSAGE);
				return false;
			} else {
				encontrado = 0;
			}
		}
		return true;
	}

	private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
		if (JOptionPane.showConfirmDialog(this, ErrorUtils.CANCELAR,
				"CANCELAR", JOptionPane.YES_NO_OPTION) == 0)
			this.dispose();

	}

	private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
		if (evt.getStateChange() == 1) {
			if (evt.getItem() == "Seleccione Corral") {
				nombreCorral = "";
			} else {
				nombreCorral = evt.getItem().toString();
			}
		}

	}

	private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
		try {
			cantidad = jTextField1.getText();
			if (StringUtils.isNullOrBlank(nombreCorral)) {
				JOptionPane.showMessageDialog(this,
						ErrorUtils.SELECCIONE_NOMBRE_CORRAL, "ERROR",
						JOptionPane.ERROR_MESSAGE);
			} else if (StringUtils.isNullOrBlank(cantidad)) {
				JOptionPane.showMessageDialog(this, ErrorUtils.CANTIDAD_VACIA,
						"ERROR", JOptionPane.ERROR_MESSAGE);
			} else if (!StringUtils.isNumber(cantidad)) {
				JOptionPane.showMessageDialog(this,
						ErrorUtils.CANTIDAD_INVALIDA, "ERROR",
						JOptionPane.ERROR_MESSAGE);
			} else {
				tabla[i][0] = nombreCorral;
				tabla[i][1] = cantidad;

				i++;
				jTable1.setModel(new javax.swing.table.DefaultTableModel(tabla,
						new String[] { "Corral", "Pesaje" }) {
					private static final long serialVersionUID = 1L;

					@Override
					public boolean isCellEditable(int fila, int columna) {
						return false;
					}
				});
				jScrollPane1.setViewportView(jTable1);
				DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
				tcr.setHorizontalAlignment(SwingConstants.CENTER);
				jTable1.getColumnModel().getColumn(0).setCellRenderer(tcr);
				jTable1.getColumnModel().getColumn(1).setCellRenderer(tcr);

				jTextField1.setText("");
				jComboBox1.setSelectedIndex(0);

			}

		} catch (Exception e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(this, ErrorUtils.ERROR_INESPERADO,
					"ERROR INESPERADO", JOptionPane.ERROR_MESSAGE);
		}

	}

	private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
		int indice = jTable1.getSelectedRow();

		if (indice == -1) {
			JOptionPane.showMessageDialog(this,
					ErrorUtils.ELIMINAR_ELEMENTO_TABLA, "ERROR",
					JOptionPane.ERROR_MESSAGE);
		} else if (StringUtils.isNullOrBlank(tabla[indice][0])) {
			JOptionPane.showMessageDialog(this,
					ErrorUtils.ELIMINAR_ELEMENTO_TABLA, "ERROR",
					JOptionPane.ERROR_MESSAGE);
		} else {
			tabla[indice][0] = "";
			tabla[indice][1] = "";

			int j;

			for (j = indice; j < i; j++) {
				tabla[j][0] = tabla[j + 1][0];
				tabla[j][1] = tabla[j + 1][1];

			}
			tabla[j][0] = "";
			tabla[j][1] = "";

			i--;
			jTable1.setModel(new javax.swing.table.DefaultTableModel(tabla,
					new String[] { "Corral", "Pesaje" }) {
				private static final long serialVersionUID = 1L;

				@Override
				public boolean isCellEditable(int fila, int columna) {
					return false;
				}
			});
			jScrollPane1.setViewportView(jTable1);
			DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
			tcr.setHorizontalAlignment(SwingConstants.CENTER);
			jTable1.getColumnModel().getColumn(0).setCellRenderer(tcr);
			jTable1.getColumnModel().getColumn(1).setCellRenderer(tcr);
		}
	}

	/**
	 * @param args
	 *            the command line arguments
	 */
	public static void main(String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run() {
				new PesajeCorralesV2().setVisible(true);
			}
		});
	}

	// Variables declaration - do not modify
	private javax.swing.JButton jButton1;
	private javax.swing.JButton jButton2;
	private javax.swing.JButton jButton4;
	private javax.swing.JButton jButton5;
	private javax.swing.JComboBox jComboBox1;
	private javax.swing.JLabel jLabel1;
	// TODO private javax.swing.JLabel jLabel2;
	private javax.swing.JLabel jLabel3;
	private javax.swing.JLabel jLabel4;
	private javax.swing.JLabel jLabel5;
	private javax.swing.JPanel jPanel1;
	private javax.swing.JScrollPane jScrollPane1;
	private javax.swing.JTable jTable1;
	private javax.swing.JTextField jTextField1;
	private javax.swing.JTextField pieDePagina;
	private String[] nombreCorrales;
	private String[][] tabla;
	private String nombreCorral;
	private String cantidad;
	private int i;
	private javax.swing.JTextField jTextField2;
	// End of variables declaration
}
